const express = require("express");
const router = express.Router();
const sharp = require('sharp');
const multer  = require('multer');
const fs = require('fs');
const path = require('path');
const jwt = require('../utils/jwt');

const base_url = 'http://gan.onecube.top:3030';

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../temp_files'));
  },
  filename: (req, file, cb) => {
    const file_name = `${Date.now()}_${file.originalname}`;
    cb(null, file_name);
  }
})
const upload = multer({ 
  storage,
  limits: { fileSize: 8 * 1024 * 1024 }
});

router.post('/file/upload', upload.single('image'), async (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1000) return;
  try {
    const file_name = req.body.file_name;
    var image_name = file_name;
    const target_path = path.join(__dirname, '../base', image_name);
    if(fs.existsSync(target_path)) {
      fs.rmSync(target_path);
      var temp = image_name.split('_');
      temp[0] = String(Date.now());
      image_name.temp.join('_');
    }

    const temp_path = req.file.path;
    const imageBuffer = fs.readFileSync(temp_path);
    const meta_data = await sharp(imageBuffer).metadata();
    const compressed = await sharp(imageBuffer)
      .resize({ 
        width: (960 < meta_data.width ? 960 : meta_data.width), 
        height: (960 < meta_data.height ? 960 : meta_data.height), 
        fit: 'inside' 
      })
    .toBuffer();
    fs.writeFileSync(target_path, compressed);
    fs.rmSync(temp_path);
    res.send({
      code: 10000,
      data: {
        imageUrl: `${base_url}/file/${image_name}`,
        thumUrl: `${base_url}/file/${image_name}?thum=true`
      }
    })
  } catch (err) {
    if (err.response) {
      res.send({ code: 20000, data: err.response.data });
    } else {
      res.send({ code: 20000, data: err });
    }
  }
})

router.post('/file/delete', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1000) return;
  const { url } = req.body;
  const regex = /\/file\/([^/]+)/;
  try {
    const match = url.match(regex);
    if (match && match[1]) {
      const imageName = match[1];
      const imagePath = path.join(__dirname, '../base', imageName);
      fs.rm(imagePath, (err) => {
        if (err) {
          return res.send({ code: 20000 });
        }
        res.send({ code: 10000 });
      });
    } else {
      res.send({ code: 10001 });
    }
  } catch (err) {
    res.send({ code: 20000 });
  }
})

router.get('/file/:image_name', async (req, res) => {
  const image_name = req.params.image_name;
  const thum = req.query.thum == 'true';
  const image_path = path.join(__dirname, `../base`, image_name);
  try {
    let output = '';
    if(fs.existsSync(image_path)) {
      const data = fs.readFileSync(image_path);
      output = data;
      output = await sharp(output)
        .resize(thum ? { width: 240, height: 240, fit: 'inside' } : null)
        .jpeg({ quality: 100 })
        .toBuffer();
    } else {
      output = fs.readFileSync(path.join(__dirname, '../base/error.jpg'));
    }
    res.set('Content-Type', `image/jpeg`);
    res.send(output);
  } catch (err) {
    output = fs.readFileSync(path.join(__dirname, '../base/error.jpg'));
    res.set('Content-Type', `image/jpeg`);
    res.send(output);
    // res.status(404).send(`err: ${err}`);
  }
})

module.exports = router;